import React, { useState } from "react";
import useSWR from "swr";
import { fetcher } from "../utils";
import { useNavigate } from "react-router-dom";

function ElectiveList() {
    const navigate = useNavigate();
    const [showModal, setShowModal] = useState(false);
    const [selectedClass, setSelectedClass] = useState("");
    const [selectedStudents, setSelectedStudents] = useState([]);
    const [isBusy, setBusy] = useState(false);
    const [actionError, setActionError] = useState(null);

    // 拉取班次、学生、选课数据
    const { data: classList } = useSWR("/api/class/list", fetcher);
    const { data: studentList } = useSWR("/api/student/list", fetcher);
    const { data: electiveList, mutate: refreshElective } = useSWR("/api/elective/list", fetcher);

    // 增加安全数组包装，防止接口异常时报错
    const safeClassList = Array.isArray(classList) ? classList : [];
    const safeStudentList = Array.isArray(studentList) ? studentList : [];

    // 辅助函数：根据sn查找名称
    const getClassName = (sn) => {
        if (!Array.isArray(classList)) return sn;
        const c = classList.find(cls => cls.sn === sn);
        return c ? c.name : sn;
    };
    const getStudentName = (sn) => {
        if (!Array.isArray(studentList)) return sn;
        const s = studentList.find(stu => stu.stu_sn === sn);
        return s ? s.stu_name : sn;
    };

    const handleStudentChange = (stu_sn) => {
        setSelectedStudents((prev) =>
            prev.includes(stu_sn)
                ? prev.filter((sn) => sn !== stu_sn)
                : [...prev, stu_sn]
        );
    };

    const handleSave = async () => {
        if (!selectedClass || selectedStudents.length === 0) {
            setActionError("请选择班次并至少选择一名学生");
            return;
        }
        setBusy(true);
        setActionError(null);
        try {
            let response = await fetch("/api/elective", {
                method: "POST",
                headers: { "Content-Type": "application/json;charset=utf-8" },
                body: JSON.stringify({ class_sn: parseInt(selectedClass), stu_sn_list: selectedStudents }),
            });
            if (!response.ok) {
                let errorText = await response.text();
                setActionError(errorText);
                return;
            }
            setShowModal(false);
            setSelectedClass("");
            setSelectedStudents([]);
            refreshElective(); // 保存后刷新选课列表
        } finally {
            setBusy(false);
        }
    };

    return (
        <div className="paper">
            <div className="paper-head">
                <div className="btn" onClick={() => navigate("/elective/new")}>新建选课</div>
            </div>
            <div className="paper-body">
                <table className="table">
                    <thead>
                        <tr>
                            <th>学生姓名</th>
                            <th>班次名称</th>
                            <th>选课时间</th>
                        </tr>
                    </thead>
                    <tbody>
                        {!Array.isArray(electiveList) && <tr><td colSpan="3">加载中...</td></tr>}
                        {Array.isArray(electiveList) && electiveList.length === 0 && <tr><td colSpan="3">暂无选课记录</td></tr>}
                        {Array.isArray(electiveList) && electiveList.map(item => (
                            <tr key={item.sn}>
                                <td>{getStudentName(item.stu_sn)}</td>
                                <td>{getClassName(item.class_sn)}</td>
                                <td>{item.elective_time}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
            {showModal && (
                <div className="modal-mask">
                    <div className="modal">
                        <div className="modal-head">新建选课</div>
                        <div className="modal-body">
                            <div className="field">
                                <label>班次：</label>
                                <select
                                    value={selectedClass}
                                    onChange={e => setSelectedClass(e.target.value)}
                                >
                                    <option value="">请选择班次</option>
                                    {safeClassList.map(cls => (
                                        <option key={cls.sn} value={cls.sn}>{cls.name}</option>
                                    ))}
                                </select>
                            </div>
                            <div className="field">
                                <label>选择学生：</label>
                                <div style={{ maxHeight: 200, overflowY: 'auto', border: '1px solid #eee', padding: 8 }}>
                                    {safeStudentList.map(stu => (
                                        <div key={stu.stu_sn}>
                                            <label>
                                                <input
                                                    type="checkbox"
                                                    value={stu.stu_sn}
                                                    checked={selectedStudents.includes(stu.stu_sn)}
                                                    onChange={() => handleStudentChange(stu.stu_sn)}
                                                />
                                                {stu.stu_name}（{stu.stu_no}）
                                            </label>
                                        </div>
                                    ))}
                                    {!studentList && <div>加载学生列表中...</div>}
                                </div>
                            </div>
                            {actionError && <div className="error">{actionError}</div>}
                        </div>
                        <div className="modal-footer">
                            <button className="btn" onClick={() => setShowModal(false)} disabled={isBusy}>取消</button>
                            <button className="btn" onClick={handleSave} disabled={isBusy}>保存</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

export default ElectiveList; 